Skip to content

Method: static {...}

1: /*
2: * JOPA
3: * Copyright (C) 2024 Czech Technical University in Prague
4: *
5: * This library is free software; you can redistribute it and/or
6: * modify it under the terms of the GNU Lesser General Public
7: * License as published by the Free Software Foundation; either
8: * version 3.0 of the License, or (at your option) any later version.
9: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library.
17: */
18: package cz.cvut.kbss.jopa.oom.converter.datetime;
19:
20: import cz.cvut.kbss.jopa.datatype.DateTimeUtil;
21: import cz.cvut.kbss.jopa.datatype.xsd.XsdDateTimeMapper;
22: import cz.cvut.kbss.jopa.oom.converter.ConverterWrapper;
23: import cz.cvut.kbss.jopa.vocabulary.XSD;
24: import cz.cvut.kbss.ontodriver.model.Literal;
25:
26: import java.time.OffsetDateTime;
27: import java.util.Date;
28:
29: /**
30: * Converts between a xsd:dateTime representation and {@link Date} instances.
31: * <p>
32: * Supported representations are {@link OffsetDateTime} and {@link Literal}.
33: * <p>
34: * Note that when transforming to axiom value, UTC time zone is assumed to provide consistent results.
35: */
36: public class DateConverter implements ConverterWrapper<Date, Object> {
37:
38: @Override
39: public Object convertToAxiomValue(Date value) {
40: assert value != null;
41: return DateTimeUtil.toDateTime(value.toInstant());
42: }
43:
44: @Override
45: public Date convertToAttribute(Object value) {
46: assert value != null;
47: if (value instanceof OffsetDateTime) {
48: return offsetDateTimeToDate((OffsetDateTime) value);
49: } else {
50: assert value instanceof Literal;
51: final Literal literal = (Literal) value;
52: assert XSD.DATETIME.equals(literal.getDatatype());
53: return offsetDateTimeToDate(XsdDateTimeMapper.map(literal.getLexicalForm()));
54: }
55: }
56:
57: private static Date offsetDateTimeToDate(OffsetDateTime value) {
58: return Date.from(value.toInstant());
59: }
60:
61: @Override
62: public boolean supportsAxiomValueType(Class<?> type) {
63: return OffsetDateTime.class.isAssignableFrom(type) || Literal.class.isAssignableFrom(type);
64: }
65: }